<template>
  <picker
    class="picker-field"
    :mode="type"
    :value="pickerValue"
    :range="formatOptions"
    range-key="label"
    :disabled="disabled"
    @change="onChange"
  >
    <van-field :value="selectedValue" right-icon="arrow" readonly placeholder="请选择" v-bind="$attrs" />
  </picker>
</template>

<script>
import { Field } from 'vant'

export default {
  components: {
    [Field.name]: Field
  },
  inheritAttrs: false,
  props: {
    type: {
      type: String,
      default: 'selector'
    },
    options: {
      type: Array,
      default: () => []
    },
    value: {
      type: [String, Number],
      required: true
    },
    labelKey: {
      type: String,
      default: 'label'
    },
    valueKey: {
      type: String,
      default: 'value'
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      selectedValue: '',
      pickerValue: ''
    }
  },
  computed: {
    formatOptions() {
      return this.options.map(option => {
        if (typeof option === 'object') {
          return {
            label: option[this.labelKey],
            value: option[this.valueKey]
          }
        }
        return {
          label: option,
          value: option
        }
      })
    }
  },
  watch: {
    value(val) {
      if (val && !this.selectedValue) {
        const value = this.type === 'selector' ? this.formatOptions.findIndex(item => item.value === (val + '')) : val
        console.log(val, value, 'formatOptions', this.formatOptions)
        this.onChange({ value }, false)
      }
    }
  },
  methods: {
    onChange(e) {
      const { value } = e.detail || e
      let result
      switch (this.type) {
        case 'selector':
          result = this.formatOptions[value]
          break
        default:
          result = { value }
          break
      }
      this.updateSelectedOption(result, value)
    },
    updateSelectedOption(option, pickerValue, emitChange = true) {
      this.selectedValue = option.label || option.value
      this.pickerValue = pickerValue
      this.$emit('input', option.value)
      emitChange && this.$emit('change', option)
    }
  }
}
</script>

<style lang="less">
.picker-field {
  position: relative;

 &::after {
    position: absolute;
    box-sizing: border-box;
    content: ' ';
    pointer-events: none;
    right: 32px;
    bottom: 0;
    left: 32px;
    border-bottom: 1px solid #ebedf0;
    -webkit-transform: scaleY(0.5);
    transform: scaleY(0.5);
    border-bottom-width: 1px;
    border-bottom-style: solid;
    border-bottom-color: rgb(235, 237, 240);
  }

  .van-cell {
    font-size: 32px;
    line-height: 48px;
    padding: 30px 40px;
    color: #646566;
  }
}
</style>
